package com.xinxin.intelligenceexam.presenter;

import com.orhanobut.logger.Logger;
import com.xinxin.intelligenceexam.api.ApiException;
import com.xinxin.intelligenceexam.api.Generator;
import com.xinxin.intelligenceexam.api.JavaExamApi;
import com.xinxin.intelligenceexam.base.BaseView;
import com.xinxin.intelligenceexam.contract.ExamContract;
import com.xinxin.intelligenceexam.domain.HttpResult;
import com.xinxin.intelligenceexam.domain.Question;
import com.xinxin.intelligenceexam.model.ExamModelImpl;

import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by x9259 on 2016/11/11
 */

public class ExamPresenterImpl implements ExamContract.Presenter {
    ExamContract.View mView;
    ExamContract.Model mModel;

    public ExamPresenterImpl() {
        mModel = new ExamModelImpl();
    }

    @Override
    public void attachView(BaseView view) {
        mView = (ExamContract.View) view;
        mView.initData();
        mView.initView();
    }

    @Override
    public void getExamQuestions(int num) {
        final Observable<HttpResult<List<Question>>> examQuestions = Generator.createService(JavaExamApi.class).getExamQuestions(num);
        examQuestions.map(new Func1<HttpResult<List<Question>>, List<Question>>() {
            @Override
            public List<Question> call(HttpResult<List<Question>> listHttpResult) {
                Logger.d(listHttpResult);
                if (listHttpResult.getStatus() == 1) {
                    return listHttpResult.getData();
                }
                throw new ApiException("未获取到内容");
            }
        }).subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        mView.showLoading(); // 需要在主线程执行
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread()) // 指定主线程
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<List<Question>>() {

            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(List<Question> questions) {
                Logger.d(questions);
                mView.startExam(questions);
            }
        });
    }
}